package com.cskaoyan.service;

import com.cskaoyan.bean.Topic;
import com.cskaoyan.bean.TopicExample;
import com.cskaoyan.mapper.TopicMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    TopicMapper topicMapper;

    @Override
    public Map<String,Object> listTopic(Integer page, Integer limit,
                                        String sort, String order,
                                        String title,String subtitle) {

        PageHelper.startPage(page,limit);
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(sort + " " + order);
        TopicExample.Criteria criteria = topicExample.createCriteria();
        if (title != null){
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !subtitle.equals("")){
            criteria.andSubtitleLike("%" + subtitle + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Topic> topicList = topicMapper.selectByExample(topicExample);
        int total = topicList.size();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("items",topicList);
        return map;
    }

    @Override
    public Topic createTopic(Topic topic) {
        topic.setSortOrder(0);
        topic.setAddTime(new Date());
        topic.setUpdateTime(new Date());
        topic.setDeleted(false);
        topicMapper.insert(topic);
        return topic;
    }

    @Override
    public Integer updateTopic(Topic topic) {
        topic.setUpdateTime(new Date());
        int update = topicMapper.updateByPrimaryKey(topic);
        return update;
    }

    @Override
    public Integer deleteTopic(Topic topic) {
        topic.setUpdateTime(new Date());
        topic.setDeleted(true);
        int update = topicMapper.updateByPrimaryKey(topic);
        return update;
    }
}
